package com.awakensoftware.hunterserver.repositories;

import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.awakensoftware.hunterserver.serverentities.Chest;
import com.vividsolutions.jts.geom.Geometry;

@Repository("chestRepository")
@Scope("singleton")
@Transactional
public class ChestRepository extends ServerEntityRepositoryBase<Chest> {

	@Override
	@Transactional(readOnly = true)	
	public Chest getById(long id) {
		return entityManager.find(Chest.class, id);
	}

	@Transactional(readOnly = true)
	public List<Chest> searchNearbyChests(double longitude, double latitude, Geometry circle) {
		return entityManager
				.createQuery("SELECT o FROM Chest o WHERE within (o.locationPoint, :circle) = true", Chest.class)
				.setParameter("circle", circle).getResultList();
	}

	// TODO: SQL Injection possible!!
	@Transactional(readOnly = true)
	public List<Chest> searchByName(String name) {
		return entityManager.createQuery("SELECT c FROM Chest c WHERE c.name LIKE :name", Chest.class)
				.setParameter("name", "%" + name + "%").getResultList();
	}

}
